<template>
<!-- 参合农民档案管理 -->
  <div class="farmer-admin-container">
    <!-- 搜索栏 -->
    <div class="search-container">
      <el-form :model="searchForm" class="search-form" label-width="80px">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="农民姓名">
              <el-input
                v-model="searchForm.name"
                placeholder="请输入农民姓名"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="身份证号">
              <el-input
                v-model="searchForm.idCard"
                placeholder="请输入身份证号"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="家庭编号">
              <el-input
                v-model="searchForm.familyId"
                placeholder="请输入家庭编号"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="农村户口">
              <el-select
                v-model="searchForm.isRural"
                placeholder="请选择是否农村户口"
                clearable
              >
                <el-option label="是" value="是" />
                <el-option label="否" value="否" />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 新增行政区域编码搜索框 -->
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="行政区域编码">
              <el-input
                v-model="searchForm.parentCode"
                placeholder="请输入行政区域编码"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="6" class="search-buttons">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="operation-buttons">
      <el-button type="primary" @click="handleAdd">
        <i class="el-icon-plus"></i> 新增农民
      </el-button>
    </div>

    <!-- 表格 -->
    <div class="table-wrapper"> <!-- 新增表格包装器 -->
      <el-table
        :data="tableData"
        border
        style="width: 100%;" 
        v-loading="loading"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column prop="farmerId" label="农民ID" width="100" align="center" />
        <el-table-column prop="name" label="姓名" width="120" align="center" />
        <el-table-column prop="idCard" label="身份证号" width="180" align="center" />
        <el-table-column prop="gender" label="性别" width="80" align="center">
          <template #default="{row}">
            <el-tag :type="row.gender === '男' ? 'primary' : 'danger'" size="small">
              {{ row.gender }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="birthDate" label="出生日期" width="120" align="center">
          <template #default="{row}">
            {{ formatDate(row.birthDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="ethnicity" label="民族" width="100" align="center" />
        <el-table-column prop="familyId" label="家庭编号" width="100" align="center" />
        <el-table-column prop="contactNumber" label="联系电话" width="120" align="center" />
        <el-table-column prop="healthStatus" label="健康状况" width="150" align="center">
          <template #default="{row}">
            <el-tooltip content="{{ row.healthStatus }}" placement="top">
              <div class="ellipsis">{{ row.healthStatus }}</div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="isRural" label="农村户口" width="100" align="center">
          <template #default="{row}">
            <el-tag :type="row.isRural === '是' ? 'success' : 'info'" size="small">
              {{ row.isRural }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="permanentAddress" label="常住住址" width="180" align="center">
          <template #default="{row}">
            <el-tooltip content="{{ row.permanentAddress }}" placement="top">
              <div class="ellipsis">{{ row.permanentAddress }}</div>
            </el-tooltip>
          </template>
        </el-table-column>
        <!-- 是否参合字段 -->
        <el-table-column prop="isCooperative" label="是否参合" width="100" align="center">
          <template #default="{row}">
            <el-tag :type="row.isCooperative === 1 ? 'success' : 'info'" size="small">
              {{ row.isCooperative === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <!-- 参合状态字段 -->
        <el-table-column prop="coopStatus" label="参合状态" width="100" align="center">
          <template #default="{row}">
            <el-tag 
              :type="row.coopStatus === 1 ? 'success' : row.coopStatus === 2 ? 'warning' : 'danger'" 
              size="small"
            >
              {{ row.coopStatus === 1 ? '正常' : row.coopStatus === 2 ? '停保' : '退保' }}
            </el-tag>
          </template>
        </el-table-column>
        <!-- 首次参合日期字段 -->
        <el-table-column prop="firstJoinDate" label="首次参合日期" width="120" align="center">
          <template #default="{row}">
            {{ row.firstJoinDate ? formatDate(row.firstJoinDate) : '-' }}
          </template>
        </el-table-column>
        <!-- 农合证号字段 -->
        <el-table-column prop="cooperativeNumber" label="农合证号" width="120" align="center">
          <template #default="{row}">
            {{ row.cooperativeNumber || '-' }}
          </template>
        </el-table-column>
        <!-- 新增行政区域编码列 -->
        <el-table-column prop="parentCode" label="行政区域编码" width="120" align="center">
          <template #default="{row}">
            {{ row.parentCode || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <el-button size="mini" type="primary" plain @click="handleEdit(row)">编辑</el-button>
            <el-button size="mini" type="danger" plain @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="700px"
      @close="resetForm"
    >
      <el-form
        :model="formData"
        :rules="formRules"
        ref="formRef"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="农民姓名" prop="name">
              <el-input v-model="formData.name" placeholder="请输入农民姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idCard">
              <el-input v-model="formData.idCard" placeholder="请输入身份证号" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="formData.gender" placeholder="请选择性别" style="width:100%">
                <el-option label="男" value="男" />
                <el-option label="女" value="女" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生日期" prop="birthDate">
              <el-date-picker
                v-model="formData.birthDate"
                type="date"
                placeholder="选择出生日期"
                style="width:100%"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="民族" prop="ethnicity">
              <el-input v-model="formData.ethnicity" placeholder="请输入民族" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="家庭编号" prop="familyId">
              <el-input-number v-model="formData.familyId" placeholder="请输入家庭编号" style="width:100%" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="农村户口" prop="isRural">
              <el-select v-model="formData.isRural" placeholder="请选择是否农村户口" style="width:100%">
                <el-option label="是" value="是" />
                <el-option label="否" value="否" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="formData.contactNumber" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="健康状况" prop="healthStatus">
          <el-input 
            v-model="formData.healthStatus" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入健康状况描述" 
          />
        </el-form-item>
        
        <el-form-item label="常住住址" prop="permanentAddress">
          <el-input 
            v-model="formData.permanentAddress" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入常住住址" 
          />
        </el-form-item>
        
        <!-- 参合相关字段 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否参合" prop="isCooperative">
              <el-radio-group v-model="formData.isCooperative">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="参合状态" prop="coopStatus">
              <el-select v-model="formData.coopStatus" placeholder="请选择参合状态" style="width:100%">
                <el-option label="正常" value="1" />
                <el-option label="停保" value="2" />
                <el-option label="退保" value="3" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="首次参合日期" prop="firstJoinDate">
              <el-date-picker
                v-model="formData.firstJoinDate"
                type="date"
                placeholder="选择首次参合日期"
                style="width:100%"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="农合证号" prop="cooperativeNumber">
              <el-input v-model="formData.cooperativeNumber" placeholder="请输入农合证号" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 新增行政区域编码字段 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="行政区域编码" prop="parentCode">
              <el-input v-model="formData.parentCode" placeholder="请输入行政区域编码" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template v-slot:footer>
          <div class="dialog-footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="submitForm">确定</el-button>
          </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'
import { formatDate } from '@/utils/date'

export default {
  name: 'FarmerAdmin',
  data() {
    // 身份证号验证
    const validateIdCard = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入身份证号'))
      }
      // 简单的身份证号验证
      const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
      if (!reg.test(value)) {
        callback(new Error('请输入正确的身份证号'))
      } else {
        callback()
      }
    }
    
    // 行政区域编码验证
    const validateParentCode = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入行政区域编码'))
      }
      // 简单验证：编码应为数字
      const reg = /^\d+$/
      if (!reg.test(value)) {
        callback(new Error('行政区域编码应为数字'))
      } else {
        callback()
      }
    }
    
    return {
      // 搜索参数
      searchForm: {
        name: '',
        idCard: '',
        familyId: '',
        isRural: '',
        isCooperative: '',
        coopStatus: '',
        // 新增搜索参数
        parentCode: ''
      },

      // 表格数据
      tableData: [],
      loading: false,

      // 分页参数
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },

      // 对话框状态
      dialogVisible: false,
      dialogTitle: '新增农民',
      formData: {
        farmerId: null,
        familyId: null,
        name: '',
        idCard: '',
        gender: '男',
        birthDate: '',
        ethnicity: '汉族',
        healthStatus: '',
        isRural: '是',
        contactNumber: '',
        permanentAddress: '',
        isCooperative: 0,
        coopStatus: 1,
        firstJoinDate: '',
        cooperativeNumber: '',
        // 新增字段
        parentCode: ''
      },

      // 表单验证规则
      formRules: {
        name: [
          { required: true, message: '请输入农民姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '姓名长度2-20位', trigger: 'blur' }
        ],
        idCard: [
          { required: true, validator: validateIdCard, trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        birthDate: [
          { required: true, message: '请选择出生日期', trigger: 'change' }
        ],
        familyId: [
          { required: true, message: '请输入家庭编号', trigger: 'blur' }
        ],
        ethnicity: [
          { required: true, message: '请输入民族', trigger: 'blur' }
        ],
        isRural: [
          { required: true, message: '请选择是否农村户口', trigger: 'change' }
        ],
        contactNumber: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$|^0\d{2,3}-?\d{7,8}$/, message: '请输入正确的联系电话', trigger: 'blur' }
        ],
        healthStatus: [
          { max: 200, message: '健康状况描述不能超过200个字符', trigger: 'blur' }
        ],
        permanentAddress: [
          { required: true, message: '请输入常住住址', trigger: 'blur' },
          { max: 200, message: '常住住址不能超过200个字符', trigger: 'blur' }
        ],
        isCooperative: [
          { required: true, message: '请选择是否参合', trigger: 'change' }
        ],
        coopStatus: [
          { required: true, message: '请选择参合状态', trigger: 'change' }
        ],
        firstJoinDate: [
          { required: true, message: '请选择首次参合日期', trigger: 'change' }
        ],
        cooperativeNumber: [
          { required: true, message: '请输入农合证号', trigger: 'blur' }
        ],
        // 新增验证规则
        parentCode: [
          { required: true, validator: validateParentCode, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    formatDate,
    
    // 获取农民列表
    fetchData() {
      this.loading = true
      request.get('/farmer/list', {
        params: {
          current: this.pagination.currentPage,
          size: this.pagination.pageSize,
          ...this.searchForm
        }
      })
      .then(res => {
        if (res.code === 200) {
          this.tableData = res.data.records
          this.pagination.total = res.data.total
        } else {
          this.$message.error(res.message || '获取数据失败')
        }
      })
      .catch(err => {
        console.error('获取农民列表失败:', err)
        this.$message.error('加载农民列表失败')
      })
      .finally(() => {
        this.loading = false
      })
    },

    // 搜索农民
    handleSearch() {
      this.pagination.currentPage = 1
      this.loading = true

      // 构建查询参数
      const queryParams = {
        current: this.pagination.currentPage,
        size: this.pagination.pageSize,
        name: this.searchForm.name || undefined,
        idCard: this.searchForm.idCard || undefined,
        familyId: this.searchForm.familyId || undefined,
        isRural: this.searchForm.isRural || undefined,
        isCooperative: this.searchForm.isCooperative || undefined,
        coopStatus: this.searchForm.coopStatus || undefined,
        // 新增搜索参数
        parentCode: this.searchForm.parentCode || undefined
      }

      // 移除空值参数
      Object.keys(queryParams).forEach(key => {
        if (queryParams[key] === undefined) {
          delete queryParams[key]
        }
      })

      request.post('/farmer/query', queryParams)
        .then(res => {
          if (res.code === 200) {
            this.tableData = res.data.records
            this.pagination.total = res.data.total
          } else {
            this.$message.error(res.message || '获取数据失败')
          }
        })
        .catch(err => {
          console.error('搜索失败:', err)
          this.$message.error('搜索失败')
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        name: '',
        idCard: '',
        familyId: '',
        isRural: '',
        isCooperative: '',
        coopStatus: '',
        // 重置新增的搜索参数
        parentCode: ''
      }
      this.handleSearch()
    },

    // 分页大小变化
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.fetchData()
    },

    // 当前页变化
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.fetchData()
    },

    // 新增农民
    handleAdd() {
      this.dialogTitle = '新增农民'
      this.resetForm()
      this.dialogVisible = true
    },

    // 编辑农民
    handleEdit(row) {
      this.dialogTitle = '编辑农民'
      this.formData = {
        ...row,
        birthDate: formatDate(row.birthDate, 'YYYY-MM-DD'),
        // 格式化日期字段
        firstJoinDate: row.firstJoinDate ? formatDate(row.firstJoinDate, 'YYYY-MM-DD') : ''
      }
      this.dialogVisible = true
    },

    // 删除单个农民
    handleDelete(row) {
      this.$confirm(`确认删除农民 "${row.name}" 吗？`, '提示', {
        type: 'warning'
      }).then(() => {
        request.post(`/farmer/delete/${row.farmerId}`)
          .then(res => {
            if (res.code === 200) {
              this.$message.success('删除成功')
              this.fetchData()
            } else {
              this.$message.error(res.message || '删除失败')
            }
          })
          .catch(err => {
            this.$message.error('删除失败')
          })
      }).catch(() => {})
    },

    // 提交表单
    submitForm() {
      this.$refs.formRef.validate(valid => {
        if (!valid) return

        const isEdit = !!this.formData.farmerId
        const apiUrl = isEdit ? '/farmer/update' : '/farmer/create'
        const method = 'post'

        request[method](apiUrl, this.formData)
          .then(res => {
            if (res.code === 200) {
              this.$message.success(`${this.dialogTitle}成功`)
              this.dialogVisible = false
              this.fetchData()
            } else {
              this.$message.error(res.message || `${this.dialogTitle}失败`)
            }
          })
          .catch(err => {
            this.$message.error(`${this.dialogTitle}失败`)
          })
      })
    },

    // 重置表单
    resetForm() {
      this.$refs.formRef && this.$refs.formRef.resetFields()
      this.formData = {
        farmerId: null,
        familyId: null,
        name: '',
        idCard: '',
        gender: '男',
        birthDate: '',
        ethnicity: '汉族',
        healthStatus: '',
        isRural: '是',
        contactNumber: '',
        permanentAddress: '',
        isCooperative: 0,
        coopStatus: 1,
        firstJoinDate: '',
        cooperativeNumber: '',
        // 重置新增字段
        parentCode: ''
      }
    }
  }
}
</script>

<style scoped>
.farmer-admin-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.search-buttons {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  height: 100%;
}

.operation-buttons {
  display:flex;
  margin-bottom: 20px;
}

.operation-buttons > * {
  margin-right: 10px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 表格样式优化 */
.el-table {
  font-size: 14px;
}

.el-table th {
  font-weight: bold;
  color: #333;
}

.el-table .cell {
  padding: 8px 0;
}

.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 新增表格包装器样式 */
.table-wrapper {
  overflow-x: auto;
  margin-bottom: 15px;
  /* 添加阴影提示用户可以横向滚动 */
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border-radius: 4px;
}

/* 为表格添加最小宽度，确保有足够的内容时才会出现滚动条 */
.el-table {
  min-width: 1300px; /* 调整最小宽度以适应新增的列 */
}

/* 响应式调整 */
@media (max-width: 768px) {
  .search-buttons {
    justify-content: flex-start;
    margin-top: 10px;
  }
  
  .el-col {
    margin-bottom: 10px;
  }
  
  .operation-buttons {
    flex-wrap: wrap;
  }
  
  .operation-buttons > * {
    margin-bottom: 10px;
  }
  
  .el-table {
    min-width: 900px; /* 减小移动设备上的最小宽度 */
  }
}
</style>